// SpaceRemover.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//

using System;
using System.Text;

namespace Bechamel
{
	public class SpaceRemover : BaseFilter<string, string>
	{
		protected override string Transformation(string input)
		{
			StringBuilder sb = new StringBuilder(input);
			sb.Replace('\n', ' ');
			sb.Replace('\t', ' ');

			for (int i = 0; i < sb.Length; i++) {
				if (sb[i] == ' ' && sb[i + 1] == ' ')
					EatSpace(sb, i + 1);
			}
			
			return sb.ToString().TrimEnd(new char[] { ' ', '\0' });
		}

		void EatSpace(StringBuilder sb, int startIndex)
		{
			int count = 1;

			// We see how much space there is 
			for (int i = startIndex + 1; sb[i]== ' ' && i < sb.Length; i++)
				count++;

			if (startIndex + count >= sb.Length)
				return;

			// We translate the string to erase the unneeded spaces
			int j = 0;
			for (j = startIndex + count; j < sb.Length; j++) {
				sb [j - count] = sb[j];
			}

			// We erase the end of the string
			for (j = j - count; j < sb.Length; j++) {
				Console.Write(j.ToString() + ", ");
				sb[j] = '\0';
			}
		}
	}
}
